package cn.wyz.org.controller;

import cn.wyz.basic.util.AjaxResult;
import cn.wyz.basic.util.PlusQueryList;
import cn.wyz.org.domain.Employee;
import cn.wyz.org.query.EmployeeQuery;
import cn.wyz.org.service.IEmployeeService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @GetMapping("getById") = @RequestMapping(value="/getById",method = RequestMethod.GET)
 * @PostMapping
 * @PutMapping
 * @PatchMapping
 * @DeleteMapping
 *
 * 使用postman来进行测试
 *
 *
 * @author Wuyuz
 * @date 2022/6/5 13:01
 */

@RestController //@Controller + @ResponseBody
@RequestMapping("/employee")
@Api(value = "员工的API",description="员工相关的CRUD功能")
public class EmployeeController {

    @Autowired
    private IEmployeeService service;

    //查询全部记录  GET
    @GetMapping
    public List<Employee> queryAll(){
        return service.selectAll();
    }

    //新的接口需要在使用  GET http 的标准来命名,具体到每一种行为对应请求
    //要在地址栏拿到拼接的数据,注解中要加入 /{对应的形参名} ,形参列表加上@pathvariable
    // 查询一条记录  GET
    @GetMapping("/{id}")
    public Employee queryById(@PathVariable("id") Long id){
        return service.selectById(id);
    }

    @DeleteMapping("/{id}")
    public AjaxResult removeById(@PathVariable("id") Long id){
        try {
            service.deleteById(id);
            return AjaxResult.make();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.make()
                    .setSuccess(false)
                    .setMessage("烂中烂,直接开摆!");
        }
    }

    //对象要在请求体当中才能拿到,所以形参列表中加的是@RequestBody
    //新增 或 修改   PUT
    @PutMapping
    public AjaxResult addOrUpdate(@RequestBody Employee dept){
        try {
            if (dept.getId() == null){
               service.insert(dept);
            } else {
                service.update(dept);
            }
            return AjaxResult.make();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.make()
                    .setSuccess(false)
                    .setMessage("烂中烂,直接开摆!");
        }
    }

    //高级查询 + 分页   POST   http://localhost:8080/dept  从请求体中获取参数
    @PostMapping
    public PlusQueryList<Employee> queryPage(@RequestBody EmployeeQuery query){
        return service.queryData(query);
    }

    @PatchMapping
    public AjaxResult patchDelete(@RequestBody List<Long> idList){
        try {
            service.patchDelete(idList);
            return AjaxResult.make();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.make()
                    .setSuccess(false)
                    .setMessage("烂中烂,直接开摆!");
        }
    }

}
